package com.epalmpay.controller.manage.operator;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import com.epalmpay.commom.BaseController;
import com.epalmpay.exception.ApplicationException;
import com.epalmpay.service.jobservice.*;
import com.epalmpay.service.weixin.IWalletService;
import com.epalmpay.status.Rescode;
import com.epalmpay.dto.system.PageDTO;
import com.epalmpay.dto.operator.SysTaskLogInDTO;
import com.epalmpay.dto.operator.SysTaskLogListOutDTO;
import com.epalmpay.entity.Page;
import com.epalmpay.entity.TradeOffline;
import com.epalmpay.enumdef.CommonEnum.RunStatus;
import com.epalmpay.enumdef.CommonEnum.TaskType;
import com.epalmpay.service.operator.ISysLogService;
import com.epalmpay.service.order.IOrderService;
import com.epalmpay.service.yunstream.IOilcardOrderService;
import com.epalmpay.util.DateUtil;
import com.epalmpay.util.Tools;

import org.springframework.web.bind.annotation.*;

/**
 * Created by wzq on 2017/6/9.
 */
@RestController
@RequestMapping("/manager/syslog")
	public class SysTaskLogController extends BaseController {

	@Resource
    private ISysLogService sysLogService;
	@Resource
	private ISaleAccountStatisService saleAccountStatisService;
	@Resource
	private IProfitStatisService profitStatisService;
	@Resource
	private IActivityTaskService activityTaskService;
	@Resource
	private ITradeStatisService tradeStatisService;
	@Resource
	private IOilcardOrderService oilCardOrderService;
	@Resource
	private IOrderService iOrderService;



	@Resource
	private IMemberRedActivityTaskService memberRedActivityTaskService;

	/**
	 * 显示计划任务列表
	 * 
	 */
	@RequestMapping(value="/listSysTaskLog")
	@ResponseBody
	public SysTaskLogListOutDTO  listSysTaskLog(SysTaskLogInDTO sysTaskLogInDTO,PageDTO pageDTO){
		SysTaskLogListOutDTO result = new SysTaskLogListOutDTO();
		try {
			Page page=Tools.pageEmtity(pageDTO);
			
			result = sysLogService.getSysTaskLogList(sysTaskLogInDTO, page);
			//此处调用重跑逻辑并记录日志等
			
			result.setPage(page); 
			result.setErrorCode(Rescode.SUCCESS, "处理成功");
			return result;
		} catch (ApplicationException ae) { 
			result.setErrorCode(ae.errCode, ae.errMsg);
			ae.printStackTrace();
			logger.error(ae);
		}
		 catch (Exception e) { 
			 result.setErrorCode(Rescode.DEFAULT_PREFIX, "处理出现异常");
			e.printStackTrace();
			logger.error(e);
		}
		return result;
	}

	/**
	 * 重跑计划任务
	 * 
	 */
	@RequestMapping(value="/sysTaskLogReRun")
	@ResponseBody
	public SysTaskLogListOutDTO  sysTaskLogReRun(SysTaskLogInDTO sysTaskLogInDTO){
		SysTaskLogListOutDTO result = new SysTaskLogListOutDTO();
		StringBuffer sb = new StringBuffer(); 
		List<TradeOffline> records;
		Date taskDate;
		try {
			//去掉接口传递过来的小时数
			taskDate = DateUtil.fomatDate(DateUtil.fomatDate(sysTaskLogInDTO.getTaskDate(),DateUtil.sdfDays),
					DateUtil.sdfDays);
			sysTaskLogInDTO.setTaskDate(taskDate);
			switch(TaskType.fromType(sysTaskLogInDTO.getTaskType())) {
				case ChannelSaleAccountDayStatis: 
					saleAccountStatisService.saveSaleAccountDayStatis(sysTaskLogInDTO.getTaskDate());
					break;
				case ProfitDayStatis: 
					profitStatisService.saveProfitDayStatis(sysTaskLogInDTO.getTaskDate());
					break;
				case TradeDayStatis:
					tradeStatisService.saveTradeDayStatis(sysTaskLogInDTO.getTaskDate());
					break;
				case ProfitDayCalculate:
					/*records = profitStatisService.selectNeedProfitList(taskDate);
					//循环处理单笔交易分润
					for (TradeOffline record : records) {
						try{
							profitStatisService.saveOneOrderProfitCalculate(record);
						} catch(Exception e){
							sysLogService.recordSysTaskLog(TaskType.ProfitDayCalculate.getType(),
									taskDate, RunStatus.Fail.getType(),
									sb.append("订单号:").append(record.getId()).append("分润计算失败！").toString());
							throw e;
						}
					}
					sysLogService.recordSysTaskLog(TaskType.ProfitDayCalculate.getType(),
							taskDate, RunStatus.Success.getType(),
							sb.append("分润计算").append(DateUtil.fomatDate(new Date(), DateUtil.sdfTime)).append("执行成功！").toString());
					*/
					break;					
				case ProfitDayRefund:
					records = profitStatisService.selectNeedProfitRefundList(taskDate);
					//循环处理单笔交易分润
					for (TradeOffline record : records) {
						try{
							profitStatisService.saveOneOrderProfitRefund(record);
						} catch(Exception e){
							sysLogService.recordSysTaskLog(TaskType.ProfitDayRefund.getType(),
									taskDate, RunStatus.Fail.getType(),
									sb.append("订单号:").append(record.getId()).append("分润退款失败！").toString());
							throw e;
						}
					}
					sysLogService.recordSysTaskLog(TaskType.ProfitDayRefund.getType(),
							taskDate, RunStatus.Success.getType(),
							sb.append("分润退款").append(DateUtil.fomatDate(new Date(), DateUtil.sdfTime)).append("执行成功！").toString());

					break;
				case ActivityDayTask:
					activityTaskService.saveActivityDayTask(sysTaskLogInDTO.getTaskDate());
					break;
				case ActivityRoutineUpdateDayTask:
					activityTaskService.saveActivityRoutineUpdateSendTask(sysTaskLogInDTO.getTaskDate());
					break;
				case ServiceGoodVerifyOutMontyDay:
					tradeStatisService.serviceGoodVerifyOutMontyDay(sysTaskLogInDTO.getTaskDate());
					break;
				case ProfitMonthStatis:
					//月份格式转换成yyyymm01格式统一处理
					taskDate = DateUtil.fomatDate(DateUtil.fomatDate(sysTaskLogInDTO.getTaskDate(),DateUtil.sdfDayss) + "01",
							DateUtil.sdfDays);
					sysTaskLogInDTO.setTaskDate(taskDate);
					profitStatisService.saveProfitMonthStatis(sysTaskLogInDTO.getTaskDate());
					break;					
				case ChannelSaleAccountMonthStatis:
					//月份格式转换成yyyymm01格式统一处理
					taskDate = DateUtil.fomatDate(DateUtil.fomatDate(sysTaskLogInDTO.getTaskDate(),DateUtil.sdfDayss) + "01",
							DateUtil.sdfDays);
					sysTaskLogInDTO.setTaskDate(taskDate);
					saleAccountStatisService.saveSaleAccountMonthStatis(sysTaskLogInDTO.getTaskDate());
					break;
				case ValidProfitSetting:
					//月份格式转换成yyyymm01格式统一处理
					taskDate = DateUtil.fomatDate(DateUtil.fomatDate(sysTaskLogInDTO.getTaskDate(),DateUtil.sdfDayss) + "01",
							DateUtil.sdfDays);
					sysTaskLogInDTO.setTaskDate(taskDate);
					profitStatisService.saveValidProfitSetting(sysTaskLogInDTO.getTaskDate());
					break;
				case ActivityMonthTask:
					//月份格式转换成yyyymm01格式统一处理
					taskDate = DateUtil.fomatDate(DateUtil.fomatDate(sysTaskLogInDTO.getTaskDate(),DateUtil.sdfDayss) + "01",
							DateUtil.sdfDays);
					sysTaskLogInDTO.setTaskDate(taskDate);
					activityTaskService.saveActivityMonthTask(sysTaskLogInDTO.getTaskDate());
					break;
				case TradeMonthStatis:
					//月份格式转换成yyyymm01格式统一处理
					taskDate = DateUtil.fomatDate(DateUtil.fomatDate(sysTaskLogInDTO.getTaskDate(),DateUtil.sdfDayss) + "01",
							DateUtil.sdfDays);
					sysTaskLogInDTO.setTaskDate(taskDate);
					tradeStatisService.saveTradeMonthStatis(sysTaskLogInDTO.getTaskDate());
					break;
				case ProfitOutMoneyMonthTask:
					//月份格式转换成yyyymm01格式统一处理
					taskDate = DateUtil.fomatDate(DateUtil.fomatDate(sysTaskLogInDTO.getTaskDate(),DateUtil.sdfDayss) + "01",
							DateUtil.sdfDays);
					sysTaskLogInDTO.setTaskDate(taskDate);
					profitStatisService.profitOutMontyMonth(sysTaskLogInDTO.getTaskDate());
					break;
				case YsOilcardChargeMonthTask:
					//月份格式转换成yyyymm01格式统一处理
					taskDate = DateUtil.fomatDate(DateUtil.fomatDate(sysTaskLogInDTO.getTaskDate(),DateUtil.sdfDayss) + "01",
							DateUtil.sdfDays);
					sysTaskLogInDTO.setTaskDate(taskDate);
					oilCardOrderService.saveOilcardChargeMonthTask(sysTaskLogInDTO.getTaskDate());
					break;
				case MemberRedActivityTask:
					sysTaskLogInDTO.setTaskDate(new Date());
					memberRedActivityTaskService.saveMemberRedActivityPerfectDayTask(sysTaskLogInDTO.getTaskDate());
					break;

				default: break;
		    }
			
			logger.info(sb.append("计划任务:")
					.append(TaskType.fromType(sysTaskLogInDTO.getTaskType()).getName())
					.append("统计日期：").append(DateUtil.fomatDate(sysTaskLogInDTO.getTaskDate(), DateUtil.sdfDays)).append("执行成功！"));

			result.setErrorCode(Rescode.SUCCESS, "处理成功");
			return result;
		
		} catch (ApplicationException ae) { 
			result.setErrorCode(Rescode.DEFAULT_PREFIX, ae.errMsg);
			logger.info(sb.append("计划任务:")
					.append(TaskType.fromType(sysTaskLogInDTO.getTaskType()).getName())
					.append("统计日期：").append(DateUtil.fomatDate(sysTaskLogInDTO.getTaskDate(), DateUtil.sdfDays)).append("执行结果：").append(ae.errMsg));
//			try{
//				sysLogService.recordSysTaskLog(sysTaskLogInDTO.getTaskType(),
//						sysTaskLogInDTO.getTaskDate(), RunStatus.Fail.getType(),ae.errMsg);
//			}catch(Exception sube){
//				logger.error(sb.append("计划任务:")
//						.append(TaskType.fromType(sysTaskLogInDTO.getTaskType()).getName())
//						.append("统计日期：").append(DateUtil.fomatDate(sysTaskLogInDTO.getTaskDate(), DateUtil.sdfDays)).append("执行失败！"));
//				logger.error(sube);
//			}
			ae.printStackTrace();
		}
		 catch (Exception e) { 
			 result.setErrorCode(Rescode.DEFAULT_PREFIX, "处理出现异常");
			 
			 try{
				sysLogService.recordSysTaskLog(sysTaskLogInDTO.getTaskType(),
						sysTaskLogInDTO.getTaskDate(), RunStatus.Fail.getType());
			 }catch(Exception sube){
					logger.error(sb.append("计划任务:")
							.append(TaskType.fromType(sysTaskLogInDTO.getTaskType()).getName())
							.append("统计日期：").append(DateUtil.fomatDate(sysTaskLogInDTO.getTaskDate(), DateUtil.sdfDays)).append("执行失败！"));				 
				 logger.error(sube);
			 }
			e.printStackTrace();
			logger.error(sb.append("计划任务:")
					.append(TaskType.fromType(sysTaskLogInDTO.getTaskType()).getName())
					.append("统计日期：").append(DateUtil.fomatDate(sysTaskLogInDTO.getTaskDate(), DateUtil.sdfDays)).append("执行失败！"));				 
			logger.error(e);
		}
		return result;
	}

}
